package se.statifyme.client.forms;

import se.statifyme.client.record.RecordClient;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;

public class DeclarationsForm extends Composite {

	interface Binder extends UiBinder<Widget, DeclarationsForm> {}

	@UiField
	HasText serviceURIField;
	@UiField
	Button submitButton;
	@UiField
	HasText statusField;
	
	private final SubmitCallback submitCallback;
	
	public DeclarationsForm() {
		initWidget(GWT.<Binder>create(Binder.class).createAndBindUi(this));
		this.submitCallback = new SubmitCallback();
		updateServiceURI();
	}
	
	@UiHandler(value = "submitButton")
	void onSubmit(ClickEvent event) {
		executeSubmit();
	}

	private void executeSubmit() {
		setEnabled(false);
		String url = buildURI();
		RecordClient.INSTANCE.get(url, submitCallback);
	}
	
	private void updateServiceURI() {
		serviceURIField.setText("GET @ " + buildURI());
	}
	
	private String buildURI() {
		return RecordClient.getServiceDeclarationsURI();
	}
	
	private void setEnabled(boolean enabled) {
		setEnabled(submitButton, enabled);
		setEnabled(statusField, enabled);
	}
	
	private void setEnabled(Object o, boolean enabled) {
		if (o instanceof HasEnabled) {
			((HasEnabled) o).setEnabled(enabled);
		}
	}
	
	private final class SubmitCallback implements AsyncCallback<String> {
		@Override
		public void onFailure(Throwable caught) {
			statusField.setText("ERROR: " + caught.getMessage());
			setEnabled(true);
		}
		@Override
		public void onSuccess(String result) {
			statusField.setText(result);
			setEnabled(true);
		}
	}
}
